package com.pktechan.manage.controller;

import com.alibaba.fastjson.JSON;
import com.pktechan.manage.entity.ReturnUploadImage;
import com.pktechan.manage.utils.FastDfsHttpUtil;
import com.pktechan.manage.utils.FileResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("pictureController")
public class PictureController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PictureController.class);

    @RequestMapping("/uploadImage")
    public String uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        ReturnUploadImage rui = null;

        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;

        MultipartFile file = multipartHttpServletRequest.getFile("upfile");

        if (file !=null){
            rui =  new ReturnUploadImage();
            rui.setTitle(file.getOriginalFilename());
            rui.setOriginal(file.getOriginalFilename());
            FileResponseData responseData = FastDfsHttpUtil.uploadFile(file);
            rui.setState("SUCCESS");
            rui.setUrl(responseData.getHttpUrl());
        }
        String result = JSON.toJSONString(rui);
        response.getWriter().write(result);
        return null;
    }

}